<?php


namespace services\base;

use Yii;
use common\helpers\ArrayHelper;
use api\modules\v1\forms\base\BbBodyPartsForm;
use common\components\Service;
use common\helpers\CommonHelper;
use common\models\base\BbBodyParts;

class BbBodyPartsService extends Service
{
    /**
     * 部位列表
     *
     * @param array $params
     * @param int $page
     * @param int $pageSize
     * @return array
     */
    public function getListPage(array $params = [], int $page = 0, int $pageSize = 0)
    {
        $query = BbBodyParts::find()->select(['*'])
            ->where([
                'pid' => 0,
                'status' => [BbBodyParts::STATUS_INVALID, BbBodyParts::STATUS_ENABLE]
            ]);

        // 总数
        $total = $query->count();

        // 分页
        if ($page && $pageSize) {
            $query->limit($pageSize)->offset(($page - 1) * $pageSize);
        }

        $list = $query
            ->orderBy(['sort' => SORT_ASC, 'id' => SORT_DESC])
            ->asArray()
            ->all();

        // 子部位
        $childList = BbBodyParts::find()->select(['*'])
            ->where([
                'pid' => array_column($list, 'id'),
                'status' => [BbBodyParts::STATUS_INVALID, BbBodyParts::STATUS_ENABLE]
            ])
            ->orderBy(['sort' => SORT_ASC, 'id' => SORT_DESC])
            ->asArray()
            ->all();
        $childListFormat = [];
        foreach ($childList as $row) {
            $childListFormat[$row['pid']][] = [
                'id' => $row['id'],
                'pid' => $row['pid'],
                'body_parts_name' => $row['body_parts_name'],
                'sort' => $row['sort'],
                'status' => $row['status'],
                'status_str' => BbBodyParts::$statuss[$row['status']],
            ];
        }

        // 格式化
        $data = [];
        foreach ($list as $row) {

            $data[] = [
                'id' => $row['id'],
                'pid' => $row['pid'],
                'body_parts_name' => $row['body_parts_name'],
                'sort' => $row['sort'],
                'status' => $row['status'],
                'status_str' => BbBodyParts::$statuss[$row['status']],
                'children' => $childListFormat[$row['id']] ?? [],
            ];
        }

        return [
            'page' => (int)$page,
            'pageSize' => (int)$pageSize,
            'total' => (int)$total,
            'list' => $data,
        ];
    }

    /**
     * 部位详情
     *
     * @param array $params
     * @return array
     */
    public function getInfo(array $params = [])
    {
        $body = BbBodyParts::findOne($params['id']);

        // 父部位
        $bodyList = BbBodyParts::find()
            ->select(['id', 'body_parts_name'])
            ->where([
                'pid' => 0,
                'status' => [BbBodyParts::STATUS_INVALID, BbBodyParts::STATUS_ENABLE]
            ])
            ->orderBy(['sort' => SORT_ASC, 'id' => SORT_DESC])
            ->asArray()
            ->all();

        return [
            'id' => $body->id ?? 0,
            'pid' => $body->pid ?? 0,
            'body_parts_name' => $body->body_parts_name ?? '',
            'sort' => $body->sort ?? 0,
            'status' => $body->status ?? BbBodyParts::STATUS_ENABLE,
            'body_list' => $bodyList,
        ];
    }

    /**
     * 新增部位
     *
     * @param BbBodyPartsForm $model
     * @return array|mixed
     */
    public function create(BbBodyPartsForm $model)
    {
        try {
            // 1.新增部位
            $body = new BbBodyParts();
            $body->pid = $model->pid;
            $body->body_parts_name = $model->body_parts_name;
            $body->status = BbBodyParts::STATUS_ENABLE;
            $body->sort = $model->sort;
            $body->created_at = time();
            $body->save();

            return ['id' => $body->id];
        } catch (\Exception $e) {
            return CommonHelper::api(422, $e->getMessage());
        }
    }

    /**
     * 编辑部位
     *
     * @param BbBodyPartsForm $model
     * @return array|mixed
     */
    public function update(BbBodyPartsForm $model)
    {
        try {
            // 1.更新部位
            $body = $model->getBody();
            $body->pid = $model->pid;
            $body->body_parts_name = $model->body_parts_name;
            $body->status = $model->status;
            $body->sort = $model->sort;
            $body->updated_at = time();
            $body->save();

            return ['id' => $body->id];
        } catch (\Exception $e) {
            return CommonHelper::api(422, $e->getMessage());
        }
    }

    /**
     * 编辑部位状态
     *
     * @param BbBodyPartsForm $model
     * @return array|mixed
     */
    public function updateStatus(BbBodyPartsForm $model)
    {
        try {
            // 1.更新部位
            $body = $model->getBody();
            $body->status = $model->status;
            $body->updated_at = time();
            $body->save();

            return ['id' => $body->id];
        } catch (\Exception $e) {
            return CommonHelper::api(422, $e->getMessage());
        }
    }

    /**
     * 真删除白白管家部位
     *
     * @param int $id
     * @return array|mixed
     */
    public function trueDelete(int $id)
    {
        $bodyPartsArray = BbBodyParts::find()
            ->select('id, body_parts_name, pid')
            ->where(['id' => $id])
            ->asArray()
            ->all();

        if (!$bodyPartsArray) {
            return ['code' => 422, 'message' => '该部位不存在'];
        }

        $transaction = Yii::$app->db->beginTransaction();
        try {

            $member = Yii::$app->user->identity->member;

            // 如果是一级部位
            if ($bodyPartsArray[0]['pid'] == 0) {

                // 需要筛选全部子集批量删除
                $childBodyParts = BbBodyParts::find()
                    ->select('id, body_parts_name, pid')
                    ->andWhere(['>', 'pid', 0])
                    ->asArray()
                    ->all();

                $childBodyArray = ArrayHelper::getChilds($childBodyParts,$id);

                foreach ($childBodyArray as $value) {
                    $bodyPartsArray[] = $value;
                }
            }

            foreach ($bodyPartsArray as $data) {
                $insertData[] = [
                    'project_id' => 0,
                    'delete_id' => $data['id'],
                    'delete_name' => $data['body_parts_name'],
                    'delete_table' => BbBodyParts::tableName(),
                    'operator_id' => $member->id,
                    'operator_name' => $member->realname,
                    'created_at' => time(),
                    'updated_at' => time()
                ];
            }

            // 删除部位表
            $ids = array_column($bodyPartsArray,'id');
            // 删除部位
            $data = BbBodyParts::deleteAll(['id' => $ids]);

            $transaction->commit();

            if (!$data) {
                return ['code' => 422, 'message' => '删除失败'];
            } else {
                return ['code' => 200, 'message' => '删除成功'];
            }

        } catch (\Exception $e) {
            $transaction->rollBack();
            return CommonHelper::api(422, $e->getMessage());
        }
    }
}
